//
//  HBProgressCircleView.swift
//  sinaWeibo
//
//  Created by Beans on 16/7/7.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

class HBProgressCircleView: UIView {

    var progress: CGFloat = 0 {
        didSet {
            // 自定义绘图的时候, 有进度的话, 需要手动调用setNeedsDisplay
            setNeedsDisplay()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clearColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func drawRect(rect: CGRect) {

        // 1. 获取绘画
        let cxtRef: CGContextRef = UIGraphicsGetCurrentContext()!

        // 2. 路径对象
        let center = CGPointMake(rect.width * 0.5, rect.height * 0.5)
        let radius = min(rect.width, rect.height) * 0.5
        let startAngle = CGFloat(0)
        let endAngle = CGFloat(M_PI * 2) * progress

        let outCirclePath: UIBezierPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        outCirclePath.addLineToPoint(center)

        let innerCirclePath: UIBezierPath = UIBezierPath(arcCenter: center, radius: radius - 5, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        innerCirclePath.addLineToPoint(center)

        // 3. 添加到上下文
        CGContextAddPath(cxtRef, outCirclePath.CGPath)
        CGContextAddPath(cxtRef, innerCirclePath.CGPath)
        // 颜色
        UIColor.redColor().set()

        // 4. 渲染
        CGContextDrawPath(cxtRef, CGPathDrawingMode.EOFill) // 奇偶填充, 留出中间的空白

        // 5. 关闭绘画
        UIGraphicsEndImageContext()
    }
}
